package org.samples.dao.imp;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.type.StringType;
import org.samples.dao.IExamSubjectDAO;
import org.samples.model.PagerModel;
import org.samples.model.ExamSubject;
import org.samples.support.SystemContext;
import org.springframework.stereotype.Repository;

@Repository
public class ExamSubjectDAOImp extends BaseHibernateDAO<ExamSubject> implements IExamSubjectDAO {

	@SuppressWarnings("unchecked")
	@Override
	public List<String> getAllUserBySubject(Integer subId) {
		StringBuilder sql = new StringBuilder();
		sql.append("select user.user_id as userId ");
		sql.append("from exam_user_subject eus ");
		sql.append("left join exam_subject es on eus.sub_id = es.sub_id ");
		sql.append("left join exam_user user on eus.user_id = user.user_id ");
		sql.append("where es.sub_id = ?; ");
		return this.createSQLQuery(String.valueOf(sql))
				.addScalar("userId", StringType.INSTANCE)
				.setInteger(0, subId)
				.list();
	}

	@Override
	public void insertSubjectUsers(List<String> list, Integer subId) {
		for(String userId : list){
			String sql = "insert into exam_user_subject values(?,?); ";
			this.createSQLQuery(sql)
				.setString(0, userId)
				.setInteger(1, subId)
				.executeUpdate();
		}
	}

	@Override
	public void deleteSubjectUsers(List<String> list, Integer subId) {
		for(String userId : list){
			String sql = "delete from exam_user_subject where user_id = ? and sub_id = ?; ";
			this.createSQLQuery(sql)
				.setString(0, userId)
				.setInteger(1, subId)
				.executeUpdate();
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public PagerModel<ExamSubject> findAll() {
		PagerModel<ExamSubject> page = new PagerModel<ExamSubject>();
		ArrayList<ExamSubject> dates = new ArrayList<ExamSubject>();
		int offset = SystemContext.getOffset();
		int pageSize = SystemContext.getSize();
		//使用hibernate完成分页
		dates = (ArrayList<ExamSubject>) this.getSession().createQuery("From ExamSubject").setFirstResult(offset).setMaxResults(pageSize).list();
		page.setDates(dates);
		page.setOffset(offset);
		page.setPageSize(pageSize);
		//获取总记录数
		long totalSize = (long) this.getSession().createQuery("select count(*) from ExamSubject ").uniqueResult();
		page.setTotalSize(totalSize);
		return page;
	}

}
